package topcbl.adapter;

import java.util.ArrayList;

import topcbl.data.FavoritePlace;
import topcbl.taxi.CallTaxiDialog;
import topcbl.taxi.MainActivity;
import topcbl.taxi.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FavoriteAdapter extends ArrayAdapter<FavoritePlace> {
	private final Activity context;
	ArrayList<FavoritePlace> data;

	public FavoriteAdapter(Activity context, ArrayList<FavoritePlace> arr) {
		super(context, R.layout.row_favorite_item, arr);
		this.context = context;
		this.data = arr;
	}

	@Override
	public View getView(final int position, View view, ViewGroup parent) {
		HolderView holder;
		if (view == null) {
			holder = new HolderView();
			LayoutInflater inflater = context.getLayoutInflater();
			view = inflater.inflate(R.layout.row_favorite_item, null, true);
			holder.txtTitle = (TextView) view.findViewById(R.id.txtPlaceName);
			holder.txtDescription = (TextView) view
					.findViewById(R.id.tvTel);
			ImageView btnDelete = (ImageView) view
					.findViewById(R.id.ImageView01);
			view.setTag(holder);
			// set event
			view.setOnClickListener(new OnItemClickListener(position));
			btnDelete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					MainActivity.myDatabase.deleteFavorite(data.get(position)
							.getId());
					data.remove(position);
					notifyDataSetChanged();
				}
			});
		} else {
			holder = (HolderView) view.getTag();
		}
		FavoritePlace place = data.get(position);
		holder.txtTitle.setText(place.getName());
		holder.txtDescription.setText(place.getNumber() + " "
				+ place.getAddress());
		return view;
	}

	static class HolderView {
		TextView txtTitle, txtDescription;
	}

	private class OnItemClickListener implements OnClickListener {
		private int mPosition;

		OnItemClickListener(int position) {
			mPosition = position;
		}

		@Override
		public void onClick(View arg0) {
			new CallTaxiDialog(context,
					(data.get(mPosition))).show();
		}
	}
}
